package teacher.action;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;

import teacher.actionform.LearnResForm;
import util.Encoding;
import dao.LearnResMagDao;
import dao.impl.LearnResMagImpl;
import domain.LearnRes;
import domain.Teacher;

/**
 * 
 * Jun 1, 2009
 *
 * @author Fabian
 * 
 * 管理课件资源
 *
 */
public class ManagerLearnResAction extends DispatchAction {
	
	/**
	 * 浏览所有课件的Action，但是要传递分页参数（start--开始，limit--间隔）
	 */
	public ActionForward show(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LearnResForm nf = (LearnResForm)form;
		int start = nf.getStart();
		int limit = nf.getLimit();		
		String flag = request.getParameter("flag");
		
		LearnResMagDao nmd = new LearnResMagImpl();
		List<LearnRes> list = null;
		int totalCount = 0;
		
		if ("experiment".equals(flag)) {
			//获取此页面的LearnRes
			list = nmd.getPageTestLearnRes(start, limit);
			//获取总记录数
			totalCount = nmd.getTestTotalCount();
		} else {
			//获取此页面的LearnRes
			list = nmd.getPageLearnRes(start, limit);
			//获取总记录数
			totalCount = nmd.getTotalCount();
		}
		
		//组装JSON字符串，返回
		String resultArray = "";
		for (Iterator<LearnRes> it = list.iterator(); it.hasNext(); ) {
			LearnRes lr = it.next();
			Date pub_time = lr.getPub_time();
			long p = pub_time.getTime();			
			
			if ("swf".equals(lr.getFormat())) {
				resultArray = resultArray + "{id: " + lr.getId() + ", title: '" + lr.getTitle() + "', res_desc: '" + 
								lr.getRes_desc() + "', format: '" + lr.getFormat() + "', size: '" + lr.getSize() + 
								"', pub_user: '" + lr.getPub_user() + "', pub_time: new Date(" + p + "), see_count:" +
								lr.getSee_count() + ", down_count: " + lr.getDown_count() + ", operate: '" + 
								"<a href=\"jsp/tch/see_online.jsp?id=" + lr.getId() + "&path=" + lr.getPath() + "\" target=\"_blank\"><img src=\"images/main/book_open.png\" alt=\"在线浏览\"/></a>" + 
								"&nbsp;&nbsp;&nbsp;&nbsp;" +
								"<a href=\"jsp/tch/download.jsp?id=" + lr.getId() + "&path=" + lr.getPath() + "\" target=\"_blank\"><img src=\"images/main/download.png\" alt=\"下载\"/></a>'}";
			} else {
				resultArray = resultArray + "{id: " + lr.getId() + ", title: '" + lr.getTitle() + "', res_desc: '" + 
				lr.getRes_desc() + "', format: '" + lr.getFormat() + "', size: '" + lr.getSize() + 
				"', pub_user: '" + lr.getPub_user() + "', pub_time: new Date(" + p + "), see_count:" +
				lr.getSee_count() + ", down_count: " + lr.getDown_count() + ", operate: '" +				
				"<a href=\"jsp/tch/download.jsp?id=" + lr.getId() + "&path=" + lr.getPath() + "\" target=\"_blank\"><img src=\"images/main/download.png\" alt=\"下载\"/></a>'}";
			}
			
			if (it.hasNext()) {
				resultArray = resultArray + ",";
			}
		}
		
		String jsonStr = "";
		jsonStr = "{totalProperty: " + totalCount + ", root: [ " + resultArray + " ]}";
		
		request.setAttribute("result", jsonStr);
				
		return mapping.findForward("show_result");
	}
	/**
	 * 添加课件
	 */
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
				
		LearnResForm lrf = (LearnResForm)form;
		String title = URLDecoder.decode(lrf.getTitle(), "utf-8");
		String res_desc = URLDecoder.decode(lrf.getRes_desc(), "utf-8");
		res_desc = res_desc.replace("\n", "");
		FormFile file = lrf.getFile_path();
		
		String flag = request.getParameter("flag");
				
		boolean result = false;
		
		if (file != null) {
			
			//设置文件名
			
			String dir = servlet.getServletContext().getRealPath("/");
			String fileName = Encoding.gbkToUTF(file.getFileName());		//解决乱码问题
			//获取扩展名
			String format = fileName.substring((fileName.lastIndexOf('.') + 1));
			if (format.length() > 4) {
				format = fileName.substring(fileName.length()-3);
			}
			//给file一个新的名字，使用UUID
			String newfileName = UUID.randomUUID().toString() + "." + format;
			
			String size = "";
			int theSize = file.getFileSize();
			int fileSize = 0;
			if (theSize > 1024) {
				fileSize = (theSize)/1024;
				size = fileSize + " KB";
			} else {
				fileSize = theSize;
				size = fileSize + " B";
			}
			Teacher tch = (Teacher)request.getSession().getAttribute("user");
			String pub_user = tch.getName();
			
			FileOutputStream fos = new FileOutputStream(dir + "resource/courseware/" + newfileName);
			fos.write(file.getFileData());
			fos.flush();
			fos.close();
			
			
			String filePath = "resource/courseware/" + newfileName;
			
			//更新数据库
			LearnRes lr = new LearnRes();
			lr.setTitle(title);
			lr.setRes_desc(res_desc);
			lr.setPath(filePath);
			lr.setFormat(format);
			lr.setSize(size);
			lr.setPub_user(pub_user);
			
			if ("experiment".equals(flag)) {
				lr.setSort("experiment");	
			} else {
				lr.setSort("courseware");	
			}
			
			LearnResMagDao lrm = new LearnResMagImpl();
			result = lrm.addLearnRes(lr);
		}
		
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{success: true, msg: '恭喜，发布课件成功！'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{failure: true, msg: '抱歉，发布课件失败！请重新尝试！'}";
			request.setAttribute("result", returnStr);
			
		}		
		
		return mapping.findForward("add_result");
	}
	
	/**
	 * 修改更新课件数据
	 */
	public ActionForward modify(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LearnResForm lrf = (LearnResForm)form;
		
		LearnRes lr = new LearnRes();
		lr.setId(lrf.getId());
		lr.setTitle(URLDecoder.decode(lrf.getTitle(), "utf-8"));
		lr.setRes_desc(URLDecoder.decode(lrf.getRes_desc(), "utf-8"));
		
		LearnResMagDao nmd = new LearnResMagImpl();
		boolean result = nmd.modifyLearnRes(lr);
		
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{success: true, msg: '恭喜，修改课件信息成功！'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{failure: true, msg: '抱歉，修改课件信息失败！请重新尝试！'}";
			request.setAttribute("result", returnStr);
			
		}		
		return mapping.findForward("modify_result");			
	}
	
	/**
	 * 删除课件
	 */
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LearnResForm lrf = (LearnResForm)form;
		
		int del_id = lrf.getId();
		
		LearnResMagDao nmd = new LearnResMagImpl();		
		
		//把课件从硬盘上删除
		LearnRes lr = nmd.getLearnRes(del_id);
		String file_path = servlet.getServletContext().getRealPath("/") + lr.getPath();
		File f = new File(file_path);
		
		boolean del_result = false;
		if (f.exists()) {
			del_result = f.delete();		
		}
		System.out.println("If File Deleted: " + del_result);
		
		//从数据库中删除
		boolean result = nmd.delLearnRes(del_id);
		
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{result: 'success', msg: '恭喜，删除课件成功！'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{result: 'failure', msg: '抱歉，删除课件失败！请重新尝试！'}";
			request.setAttribute("result", returnStr);
			
		}		
		
		return mapping.findForward("del_result");
	}
}
